import { DINGTALK_APPID, DINGTALK_REDIRECT_URI } from '@/constants/config';

let auths = [];
let scan = null; // 扫码
let isOpen = false; // 闪光灯是否开始标志 true:闪光灯已经开启 false:闪光灯关闭
let nw;

mui.init();

mui.plusReady(() => {
  plus.oauth.getServices((services) => {
    auths = services;
  });
});

/*
钉钉登录
*/
export function dingTalkLogin() {
  return new Promise((resolve, reject) => {
    let code;
    let state;
    nw = mui.openWindow({
      url: `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${DINGTALK_APPID}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${DINGTALK_REDIRECT_URI}`,
      id: `dingTalk${new Date().getTime()}`,
      styles: {
        titleNView: {
          titleText: '钉钉登录',
          buttons: [
            {
              type: 'back',
              float: 'left',
              onclick() {
                closeDingTalk();
              },
            },
          ],
        },
      },
    });
    nw.appendJsFile('_www/js/mui.js');
    nw.overrideUrlLoading({
      mode: 'allow',
      match: '.*dingtalk\.com/.*',
    }, (e) => {
      code = getParam(e.url, 'code');
      state = getParam(e.url, 'state');
      resolve({
        code,
        state,
      });
      closeDingTalk();
    });
  });
}


/**
 * 关闭钉钉
 */
function closeDingTalk() {
  nw.close();
}


/**
 * 第三方登录获取用户信息
 * @param type
 * @returns {Promise<any>}
 */
export function authLogin(type) {
  return new Promise((resolve, reject) => {
    if (!window.plus) return;
    let s;
    for (let i = 0; i < auths.length; i++) {
      if (auths[i].id == type) {
        s = auths[i];
        break;
      }
    }
    if (!s.authResult) {
      s.login((e) => {
        const res = Object.assign({}, e.target);
        console.log(JSON.stringify(res));
        resolve(res);
        authLogout();
      }, (e) => {
        reject(e);
      });
    }
  });
}

/**
 * 第三方授权注销
 */
export function authLogout() {
  if (!window.plus) return;
  for (let i = 0; i < auths.length; i++) {
    const s = auths[i];
    if (s.authResult) {
      s.logout((e) => {
        // console.log("注销登录认证成功！");
      }, (e) => {
        // ("注销登录认证失败！");
      });
    }
  }
}


/**
 *开始扫描
 */
export function startScan(domId) {
  return new Promise(((resolve, reject) => {
    if (!window.plus) return;

    if (!scan) {
      let filter;
      // 创建扫描控件
      scan = new plus.barcode.Barcode(domId, filter, {
        height: '70000px',
        position: 'absolute',
      });
      // 扫描结果
      scan.onmarked = function (type, result) {
        let text = '未知: ';
        switch (type) {
          case plus.barcode.QR:
            text = 'QR: ';
            break;
          case plus.barcode.EAN13:
            text = 'EAN13: ';
            break;
          case plus.barcode.EAN8:
            text = 'EAN8: ';
            break;
        }
        resolve({
          type,
          result,
        });
      };
    }
    scan.start();
  }));
}

/**
 *取消扫描
 */
export function cancelScan() {
  if (!window.plus) return;
  scan.cancel();
}

/**
 * 关闭扫描
 */
export function closeScan() {
  if (!window.plus) return;
  scan.close();
  scan = null;
}

/**
 *开启和关闭闪光灯
 */
export function setFlash() {
  if (!window.plus) return;
  isOpen = !isOpen;
  if (isOpen) {
    scan.setFlash(true);
  } else {
    scan.setFlash(false);
  }
}

/** *
 * 获取url参数
 * @param url
 * @param paraName
 * @returns {string}
 */
function getParam(url, paraName) {
  const arrObj = url.split('?');
  if (arrObj.length > 1) {
    const arrPara = arrObj[1].split('&');
    let arr;
    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=');
      if (arr != null && arr[0] == paraName) {
        return arr[1];
      }
    }
    return '';
  }

  return '';
}
